<?php

namespace App\Admin\Auth;

use App\admin\BaseController;
use App\Http\Models\AdminNode;
use App\Utils\Code;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/**
 * 节点控制器
 */
class NodesController extends BaseController
{
	
	/**
	 * 节点首页显示
	 */	
	public function index()
	{
		return view('admin/nodes/index', ['list' => json_encode([]), 'count' => 1]);
	}

	/**
	 * 获取节点列表
	 */
	public function getList()
	{
		$nodeList = AdminNode::all()->toArray();
		return renderData($nodeList);
	}

	/**
	 * 编辑节点显示
	 */
	public function edit($pid, $id = false)
	{
		$nodeList = AdminNode::where(['pid' => 0]) -> get() -> toArray();
		$node = [];
		if (!$id && $pid) $node['pid'] = $pid;
		if ($id) $node = AdminNode::find($id)->toArray();
		return view('admin/nodes/edit', ['node' => $node, 'nodeList' => $nodeList]);
	}

	/**
	 * 保存节点
	 */
	public function save(Request $request)
	{
		$data = $request->input();
		if (isset($data['id']) && $data['id']) {
			$adminNode = AdminNode::find($data['id']);
			$result = $adminNode->fill($data)->save(); 
		} else {
			$adminNode = new AdminNode();
			$result = $adminNode->fill($data)->save();
		}
		if ($result) {
			return renderSuccess('保存成功');
		}

		return renderError(Code::SAVE_FAILED);
	}

	/**
	 * 删除节点
	 */
	public function delete($id)
	{
		if (!$id) return renderError(Code::PARAM_IS_ERROR);
		$node = AdminNode::find($id);
		if (!$node) {
			return renderError(Code::FAILED_TO_FIND_DATA);
		} 
		if ($node->delete()) {
			return renderSuccess('删除节点成功');
		} else {
			return renderError(Code::DELETE_FAILED);
		}
	}

	/**
	 * 获取菜单
	 */
	public static function getMenu()
	{
		$route = Route::currentRouteName();
		$menuList = AdminNode::where(['is_menu' => 1]) -> orderBy('sort', 'asc') -> get() -> toArray();
		$menuList = createMenu($menuList, $route);
		return $menuList;
	}

}